<template>
  <div class="business">
    <el-card>
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="80px"
        :inline="true"
        :key="1"
      >
        <el-form-item label="工单编号">
          <el-input
            placeholder="请输入"
            v-model="form.taskCode"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="工单状态">
          <el-select v-model="form.status" placeholder="请选择" clearable>
            <el-option
              :label="item.statusName"
              :value="item.statusId"
              v-for="item in taskStatus"
              :key="item.statusId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            icon="el-icon-search"
            style="background: #5f84ff; color: #fff"
            @click="searchTask"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <template slot="header">
        <el-button
          icon="el-icon-circle-plus-outline"
          class="orange"
          @click="newCreate('new')"
          >新建</el-button
        >
        <el-button class="rouse" @click="taskSetting">工单配置</el-button>
      </template>

      <el-dialog
        :visible.sync="dialogVisible5"
        width="32%"
        round
        :close-on-click-modal="false"
      >
        <h3 slot="title">工单配置</h3>
        <el-form ref="warnForm" :model="warnForm" :rules="warnRules" :key="2">
          <el-form-item label="补货警戒线" prop="alertValue">
            <el-input-number
              controls-position="right"
              :min="0"
              :max="100"
              v-model="warnForm.alertValue"
              size="large"
              style="width: 396px"
            ></el-input-number>
          </el-form-item>
          <el-form-item style="padding-left: 180px">
            <el-button class="rouse" @click="dialogVisible5 = false"
              >取消</el-button
            >
            <el-button class="orange" @click="settingAlert">确认</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <el-table :data="taskList" style="width: 100%">
        <el-table-column
          type="index"
          :index="index"
          label="序号"
          width="80"
        ></el-table-column>
        <el-table-column
          prop="taskCode"
          label="工单编号"
          width="223"
        ></el-table-column>
        <el-table-column
          prop="innerCode"
          label="设备编号"
          width="223"
        ></el-table-column>
        <el-table-column
          prop="taskType.typeName"
          label="工单类型"
          width="223"
        ></el-table-column>
        <el-table-column
          prop="createType"
          label="工单方式"
          width="223"
        ></el-table-column>
        <el-table-column
          prop="taskStatusTypeEntity.statusName"
          label="工单状态"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="userName"
          label="运营人员"
          width="223"
        ></el-table-column>
        <el-table-column
          prop="createTime"
          label="创建日期"
          width="160"
        ></el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button type="text" @click="getTaskDetail(row.taskId)"
              >查看详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="footer" v-show="showFooter">
        <span
          >共{{ totalCount }}条记录 第{{ params.pageIndex }}/{{
            totalPage
          }}页</span
        >
        <div class="btn">
          <el-button :disabled="params.pageIndex === 1" @click="prevPage"
            >上一页</el-button
          >
          <el-button @click="nextPage">下一页</el-button>
        </div>
      </div>
    </el-card>

    <el-dialog
      :visible.sync="dialogVisible1"
      width="32%"
      round
      :close-on-click-modal="false"
    >
      <h3 slot="title">工单详情</h3>
      <div class="status" style="background: #f8f8f8">
        <el-result
          icon="success"
          title="完成"
          v-if="taskDetail.taskStatusTypeEntity?.statusName === '完成'"
          :key="1"
        >
          <template #extra>
            <img :src="baseUrl + '/img/pic_2.3b5af41c.png'" alt />
          </template>
        </el-result>
        <el-result
          icon="info"
          title="取消"
          v-else-if="taskDetail.taskStatusTypeEntity?.statusName === '取消'"
          :key="2"
        >
          <template #extra>
            <img :src="baseUrl + '/img/pic_3.e8208e34.png'" alt />
          </template>
        </el-result>
        <el-result
          title="待办"
          v-else-if="taskDetail.taskStatusTypeEntity?.statusName === '待办'"
          :key="3"
        >
          <template #icon>
            <i class="el-icon-alarm-clock"></i>
          </template>
          <template #extra>
            <img :src="baseUrl + '/img/pic_1.834b274c.png'" alt />
          </template>
        </el-result>
        <el-result icon="warning" title="进行" v-else :key="4">
          <template #extra>
            <img :src="baseUrl + '/img/pic_2.3b5af41c.png'" alt />
          </template>
        </el-result>
      </div>
      <div>
        <el-descriptions :column="2">
          <el-descriptions-item label="设备编号">{{
            taskDetail?.innerCode
          }}</el-descriptions-item>
          <el-descriptions-item label="创建日期">{{
            taskDetail?.createTime
          }}</el-descriptions-item>
          <el-descriptions-item label="取消日期">{{
            taskDetail?.updateTime
          }}</el-descriptions-item>
          <el-descriptions-item label="运维人员">{{
            taskDetail?.userName
          }}</el-descriptions-item>
          <el-descriptions-item label="工单类型">{{
            taskDetail?.taskType?.typeName
          }}</el-descriptions-item>
          <el-descriptions-item label="补货数量">
            <el-button
              type="text"
              style="padding: 0"
              @click="getGoodsDetail(taskDetail.taskId)"
              >补货详情</el-button
            >
          </el-descriptions-item>
          <el-descriptions-item label="工单方式">{{
            taskDetail?.createType ? '手动' : '自动'
          }}</el-descriptions-item>
          <el-descriptions-item label="取消原因"></el-descriptions-item>
        </el-descriptions>
      </div>
      <span slot="footer">
        <el-button
          @click="newCreate('rew', taskDetail.taskId)"
          v-if="taskDetail?.taskStatusTypeEntity?.statusId === 3"
          >重新创建</el-button
        >
        <el-button @click="cancelTask(taskDetail.taskId)" v-else
          >取消工单</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogVisible2"
      width="32%"
      round
      :close-on-click-modal="false"
    >
      <h3 slot="title">补货详情</h3>
      <el-scrollbar style="height: 320px">
        <el-table :data="goodsList" style="width: 100%">
          <el-table-column
            prop="channelCode"
            label="货道编号"
          ></el-table-column>
          <el-table-column prop="skuName" label="商品"></el-table-column>
          <el-table-column
            prop="expectCapacity"
            label="补货数量"
          ></el-table-column>
        </el-table>
      </el-scrollbar>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogVisible3"
      width="32%"
      round
      :close-on-click-modal="false"
      ref="addform"
      @close="clearForm"
    >
      <h3 slot="title">新增工单</h3>
      <el-form
        ref="addform"
        :model="addform"
        label-width="80px"
        :rules="rules"
        :key="3"
      >
        <el-form-item label="设备编号" prop="innerCode">
          <el-input
            type="text"
            placeholder="请输入设备编号"
            v-model="addform.innerCode"
            maxlength="15"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="工单类型" prop="productType">
          <el-select v-model="addform.productType" placeholder="请选择工单类型">
            <el-option
              :label="item.typeName"
              :value="item.type"
              v-for="item in taskTypes"
              :key="item.typeId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="补货数量">
          <el-button
            type="text"
            style="padding: 0; text-align: center; color: #6b8dff"
            icon="el-icon-edit-outline"
            @click="getDetails"
            >补货清单</el-button
          >
        </el-form-item>
        <el-form-item label="运营人员" prop="userName">
          <el-select v-model="addform.userName" placeholder="请选择运营人员">
            <el-option label="运营石凯安" value="运营石凯安"></el-option>
            <el-option label="运营邱元明" value="运营邱元明"></el-option>
            <el-option label="吴冠霖" value="吴冠霖"></el-option>
            <el-option label="运营刘俊杰" value="运营刘俊杰"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="desc">
          <el-input
            type="textarea"
            placeholder="请输入备注（不超过40字）"
            v-model="addform.desc"
            maxlength="40"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item style="padding-left: 100px">
          <el-button class="rouse" @click="cancelAdd">取消</el-button>
          <el-button class="orange" @click="confirmAdd">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogVisible4"
      width="35%"
      round
      :close-on-click-modal="false"
    >
      <h3 slot="title">补货详情</h3>
      <el-scrollbar style="height: 320px">
        <el-table :data="details" style="width: 100%">
          <el-table-column
            prop="channelCode"
            label="货道编号"
            width="80"
          ></el-table-column>
          <el-table-column
            prop="sku.brandName"
            label="商品名称"
            width="130"
          ></el-table-column>
          <el-table-column
            prop="currentCapacity"
            label="当前数量"
            width="80"
          ></el-table-column>
          <el-table-column
            prop="purlusCapacity"
            label="还可添加"
            width="80"
          ></el-table-column>
          <el-table-column label="补满数量" width="150">
            <template slot-scope="{ row }">
              <el-input-number
                :value="row.expectCapacity"
                size="small"
                :min="0"
                :max="row.purlusCapacity"
                @change="handleChange($event, row.channelCode)"
                controls-position="right"
              ></el-input-number>
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllTaskStatus,
  getAllTaskType,
  getTaskList,
  getTaskDetail,
  getGoodsList,
  addTask,
  getGoodsDetail,
  getAlert,
  setAlert,
  cancelTask
} from '@/apis/task'
import { Message } from 'element-ui'
import { mapState } from 'vuex'
import { dealList, setPagination } from '@/utils/other'
export default {
  name: 'business-page',
  components: {},
  props: {},
  data() {
    return {
      params: {
        pageIndex: 1,
        pageSize: 10,
        isRepair: false
      },
      taskStatus: [],
      taskTypes: [],
      taskList: [],
      form: {
        taskCode: '',
        status: ''
      },
      warnForm: {
        alertValue: 50
      },
      warnRules: {
        alertValue: [
          { required: true, message: '警戒线阈值不能为空', trigger: 'blur' },
          {
            min: 0,
            max: 100,
            message: '请输入正确的警戒线阈值',
            trigger: 'blur'
          }
        ]
      },
      addform: {
        createType: 1,
        innerCode: '',
        userId: 1,
        assignorId: 45,
        productType: '',
        userName: '',
        desc: ''
      },
      goodsList: [],
      totalCount: '',
      totalPage: '',
      taskDetail: {},
      details: [],
      rules: {
        innerCode: [
          { required: true, message: '请输入设备编号', trigger: 'blur' },
          { min: 8, max: 15, message: '请输入正确的设备编号', trigger: 'blur' }
        ],
        productType: [
          { required: true, message: '请选择工单类型', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '请选择运营人员', trigger: 'blur' }
        ],
        desc: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      dialogVisible1: false,
      dialogVisible2: false,
      dialogVisible3: false,
      dialogVisible4: false,
      dialogVisible5: false
    }
  },
  computed: {
    showFooter() {
      return this.totalPage > 1
    },
    ...mapState(['baseUrl'])
  },
  watch: {},
  created() {
    this.getTaskStatus()
    this.getTaskList(this.params)
  },
  beforeMount() {
    this.getAllTaskType()
  },
  methods: {
    async getTaskStatus() {
      const res = await getAllTaskStatus()
      this.taskStatus = res
    },
    async getAllTaskType() {
      const res = await getAllTaskType()
      this.taskTypes = res
    },
    async getTaskList(value) {
      const res = await getTaskList(value)
      setPagination(this, res)
      this.taskList = dealList(res.currentPageRecords)
    },
    async searchTask() {
      await this.getTaskList({ ...this.form, ...this.params })
    },
    async taskSetting() {
      this.dialogVisible5 = true
      const res = await getAlert(this.warnForm)
      this.warnForm.alertValue = res
    },
    async settingAlert() {
      await setAlert(this.warnForm)
      Message.success('设置预警阈值成功')
      this.dialogVisible5 = false
    },
    prevPage() {
      this.params.pageIndex -= 1
      this.getTaskList(this.params)
    },
    nextPage() {
      this.params.pageIndex += 1
      this.getTaskList(this.params)
    },
    index(index) {
      return (this.params.pageIndex - 1) * 10 + index + 1
    },
    async getTaskDetail(id) {
      this.dialogVisible1 = true
      const res = await getTaskDetail(id)
      this.taskDetail = res
      this.taskDetail.createTime = this.taskDetail.createTime.replace(/T/, ' ')
      this.taskDetail.updateTime = this.taskDetail.updateTime.replace(/T/, ' ')
    },
    async getGoodsDetail(id) {
      const res = await getGoodsDetail(id)
      this.dialogVisible2 = true
      this.goodsList = res
    },
    clearForm() {
      this.$refs.addform.resetFields()
      this.addform.innerCode = ''
      this.addform.userName = ''
      this.addform.desc = ''
      this.addform.productType = ''
      this.addform.taskType = {}
    },
    newCreate(type, id) {
      this.dialogVisible1 = false
      this.dialogVisible3 = true
      if (type === 'rew') {
        this.addform.innerCode = this.taskDetail.innerCode
        this.addform.userName = this.taskDetail.userName
      }
    },
    async cancelTask(id) {
      try {
        await this.$confirm('取消工单后，将无法恢复，是否确认取消?', '', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        })
        await cancelTask(id)
        Message.success('取消工单成功')
        await this.getTaskList(this.params)
      } catch (error) {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
    },
    cancelAdd() {
      this.dialogVisible3 = false
    },
    async confirmAdd() {
      try {
        await this.$refs.addform.validate()
        if (this.addform.productType === 2) {
          this.form.details = this.details
        }
        await addTask(this.addform)
        this.getTaskList(this.form)
      } catch (error) {
        Message(error.response?.data)
      }
      this.dialogVisible3 = false
    },
    async getDetails() {
      try {
        await this.$refs.addform.validateField(
          'innerCode',
          async (innerCodeError) => {
            if (!innerCodeError) {
              this.dialogVisible4 = true
              const res = await getGoodsList(this.taskDetail.innerCode)
              this.details = res.map((item) => {
                item.purlusCapacity = item.maxCapacity - item.currentCapacity
                item.expectCapacity = item.purlusCapacity
                return item
              })
            } else {
              return false
            }
          }
        )
      } catch (error) {
        return Promise.reject(error)
      }
    },
    handleChange(value, id) {
      this.details = this.details.map((item) => {
        if (item.channelCode === id) {
          this.$set(item, 'expectCapacity', value)
        }
        return item
      })
    }
  }
}
</script>

<style scoped lang="scss">
.business {
  padding: 20px;
  background-color: #f8fafd;
}
.el-card:first-child {
  margin-bottom: 20px;
  ::v-deep .el-card__body {
    padding: 10px;
    .el-form-item {
      margin-bottom: 0;
    }
  }
}
.orange {
  background-image: linear-gradient(135deg, #ff9949, #ff6021);
  color: #fff;
  font-size: 14px;
}
.rouse {
  background-color: #fbf4f0;
}
.footer {
  height: 96px;
  padding: 32px 16px;
  box-sizing: border-box;
  span {
    float: left;
    color: #dbe2ec;
  }
  .btn {
    float: right;
    .el-button {
      width: 70px;
      height: 32px;
      padding: 0;
      text-align: center;
      line-height: 32px;
      background-color: #d5ddf8;
    }
  }
}
.el-table {
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica Neue,
    Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif;
}
::v-deep .el-table__cell {
  border-bottom: 0 !important;
  padding: 2px 0;
}
::v-deep .el-dialog__wrapper {
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica Neue,
    Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif;
  .el-dialog {
    border-radius: 10px !important;
    min-height: 215px;
    max-height: 630px;
    .el-dialog__header h3 {
      font-size: 16px;
    }
    .el-dialog__body {
      padding: 20px 60px;
      .el-scrollbar > div {
        overflow-x: hidden;
        .el-table__header-wrapper {
          th {
            background-color: #f3f6fb;
            line-height: 1.15;
            color: #666;
            font-weight: 500;
            text-align: center;
            padding: 10px 0 9px;
          }
        }
        table {
          td {
            text-align: center;
          }
        }
      }
    }
    .el-dialog__footer {
      text-align: center;
      .el-button {
        background-color: #fbf4f0;
      }
    }
  }
}
.el-form-item__content {
  position: relative;
  .el-input__count {
    position: absolute;
    bottom: 5px;
    right: 5px;
    color: #ccc;
  }
}
.el-select {
  width: 415px;
}
.el-result {
  display: flex;
  justify-content: flex-start;
  flex-wrap: nowrap;
  flex-direction: row;
  align-items: center;
  height: 54px;
  padding: 0;
  margin-bottom: 25px;
  ::v-deep .el-result__icon {
    margin-left: 22px;
    .icon-info,
    .icon-success,
    .icon-warning {
      width: 30px;
      height: 30px;
    }
  }
  ::v-deep .el-result__title {
    width: 360px;
    margin-top: 0;
    margin-left: 16px;
    p {
      text-align: left;
      line-height: 54px;
      font-size: 14px;
    }
  }
  ::v-deep .el-result__extra {
    margin-top: -10px;
  }
  ::v-deep .el-icon-alarm-clock {
    width: 26px;
    height: 26px;
    border-radius: 50%;
    background-color: #ff665f;
    font-size: 20px;
    line-height: 26px;
    color: #fff;
  }
}
</style>
